package cn.edu.scau.cmi.wujiaxian.comprehension.client;

import java.net.URL;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Optional;
import java.util.ResourceBundle;

import org.springframework.context.ApplicationContext;

import cn.edu.scau.cmi.wujiaxian.comprehension.dao.StudentDAO;
import cn.edu.scau.cmi.wujiaxian.comprehension.dao.TeacherDAO;
import cn.edu.scau.cmi.wujiaxian.comprehension.domain.Student;
import cn.edu.scau.cmi.wujiaxian.comprehension.domain.Teacher;
import cn.edu.scau.cmi.wujiaxian.comprehension.util.ComprehensionApplicationContextUtil;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextInputDialog;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.stage.StageStyle;

public class Index implements Initializable {

	private StudentDAO studentDAO;

	private TeacherDAO teacherDAO;

	/**
	 * 缓冲的操作信息
	 */
	private String last = "";

	@FXML
	public VBox container;

	@FXML
	public TextArea textArea;

	@Override
	public void initialize(URL location, ResourceBundle resources) {
		ApplicationContext applicationContext = ComprehensionApplicationContextUtil.getApplicationContext();
		studentDAO = (StudentDAO) applicationContext.getBean("studentDAO");
		teacherDAO = (TeacherDAO) applicationContext.getBean("teacherDAO");
	}

	/**
	 * 添加学生
	 * 
	 * @param actionEvent
	 * @throws Exception
	 */
	public void onAddStudent(ActionEvent actionEvent) throws Exception {
		TextInputDialog dialog = new TextInputDialog();
		dialog.setTitle("添加学生");
		dialog.setHeaderText(null);
		dialog.setContentText("学生名字");
		Optional<String> result = dialog.showAndWait();
		// 用户点击取消
		if (!result.isPresent()) {
			return;
		}
		Student student = new Student();
		student.setName(result.get());
		try {
			studentDAO.save(student);
			pushToTextArea("添加学生：" + result.get() + "成功");
		} catch (RuntimeException e) {
			pushToTextArea("添加学生失败");
		}
	}

	/**
	 * 修改学生信息
	 * 
	 * @param actionEvent
	 * @throws Exception
	 */
	public void onUpdateStudent(ActionEvent actionEvent) throws Exception {
		Stage stage = new Stage();
		stage.initStyle(StageStyle.TRANSPARENT);
		new Application() {
			@Override
			public void start(Stage primaryStage) throws Exception {
				DoubleInputDialog doubleInputDialog = new DoubleInputDialog("学生编号", "新名字", "修改学生", primaryStage);
				doubleInputDialog.setConfirmButtonAction(onUpdateStudentComfirm(doubleInputDialog, primaryStage));
				Scene scene = new Scene(doubleInputDialog);
				primaryStage.setScene(scene);
				primaryStage.show();
			}
		}.start(stage);
	}

	/**
	 * 添加学生点击确认按钮时触发的事件
	 * 
	 * @param doubleInputDialog
	 * @return
	 */
	public EventHandler<ActionEvent> onUpdateStudentComfirm(DoubleInputDialog doubleInputDialog, Stage stage) {
		return action -> {
			Long id = Long.valueOf(doubleInputDialog.getTextField1().getText());
			Student student = studentDAO.findById(id);
			student.setName(doubleInputDialog.getTextField2().getText());
			try {
				studentDAO.update(student);
				pushToTextArea("更新学生" + id + "信息成功");
				if (student.getTutor() != null) {
					student.setTeacher(teacherDAO.findById(student.getTutor()));
				}
				pushToTextArea("新信息是" + student);
			} catch (RuntimeException e) {
				pushToTextArea("更新失败");
			}
			stage.close();
		};
	}

	/**
	 * 删除学生
	 * 
	 * @param actionEvent
	 */
	public void onDeleteStudent(ActionEvent actionEvent) {
		TextInputDialog dialog = new TextInputDialog();
		dialog.setTitle("删除学生");
		dialog.setHeaderText(null);
		dialog.setContentText("学生编号");
		Optional<String> result = dialog.showAndWait();
		// 用户点击取消
		if (!result.isPresent()) {
			return;
		}
		Student student = new Student();
		student.setId(Long.valueOf(result.get()));
		try {
			studentDAO.delete(student);
			pushToTextArea("删除学生编号" + result.get() + "成功");
		} catch (RuntimeException e) {
			pushToTextArea("删除学生失败");
		}
	}

	/**
	 * 搜索学生的指导老师
	 * 
	 * @param actionEvent
	 */
	public void onChooseTutor(ActionEvent actionEvent) {
		TextInputDialog dialog = new TextInputDialog();
		dialog.setTitle("搜索学生的指导老师");
		dialog.setHeaderText(null);
		dialog.setContentText("学生编号");
		Optional<String> result = dialog.showAndWait();
		// 用户点击取消
		if (!result.isPresent()) {
			return;
		}
		Long id = Long.valueOf(result.get());
		try {
			Student student = studentDAO.findById(id);
			if (student == null || student.getTutor() == null) {
				pushToTextArea("选择学生的指导老师失败，学生或学生的指导老师不存在");
			} else {
				Teacher teacher = teacherDAO.findById(student.getTutor());
				pushToTextArea(teacher.toString());
				pushToTextArea("他的学生如下");
				for (Object o : studentDAO.findByProperty("tutor", student.getTutor())) {
					pushToTextArea(o.toString());
				}
				pushToTextArea("他的学生如上");
			}
		} catch (RuntimeException e) {
			pushToTextArea("选择学生的指导老师失败");
		}
	}

	/**
	 * 更新学生的指导老师
	 * 
	 * @param actionEvent
	 * @throws Exception
	 */
	public void onUpdateTutor(ActionEvent actionEvent) throws Exception {
		Stage stage = new Stage();
		stage.initStyle(StageStyle.TRANSPARENT);
		new Application() {
			@Override
			public void start(Stage primaryStage) throws Exception {
				DoubleInputDialog doubleInputDialog = new DoubleInputDialog("学生编号", "新老师编号", "更新学生的指导老师",
						primaryStage);
				doubleInputDialog.setConfirmButtonAction(onUpdateTutorComfirm(doubleInputDialog, primaryStage));
				Scene scene = new Scene(doubleInputDialog);
				primaryStage.setScene(scene);
				primaryStage.show();
			}
		}.start(stage);
	}

	/**
	 * 添加学生点击确认按钮时触发的事件
	 * 
	 * @param doubleInputDialog
	 * @return
	 */
	public EventHandler<ActionEvent> onUpdateTutorComfirm(DoubleInputDialog doubleInputDialog, Stage stage) {
		return action -> {
			Long id = Long.valueOf(doubleInputDialog.getTextField1().getText());
			Student student = studentDAO.findById(id);
			Long tutor = Long.valueOf(doubleInputDialog.getTextField2().getText());
			student.setTutor(tutor);
			try {
				studentDAO.update(student);
				pushToTextArea("更新学生" + id + "信息成功");
				pushToTextArea("新学生信息是" + student);
				if (student.getTutor() != null) {
					pushToTextArea("新指导老师是：");
					pushToTextArea(teacherDAO.findById(student.getTutor()).toString());
				}
			} catch (RuntimeException e) {
				pushToTextArea("更新失败");
			}
			stage.close();
		};
	}

	/**
	 * 添加老师
	 * 
	 * @param actionEvent
	 */
	public void onAddTeacher(ActionEvent actionEvent) {
		TextInputDialog dialog = new TextInputDialog();
		dialog.setTitle("添加老师");
		dialog.setHeaderText(null);
		dialog.setContentText("老师名字");
		Optional<String> result = dialog.showAndWait();
		// 用户点击取消
		if (!result.isPresent()) {
			return;
		}
		Teacher teacher = new Teacher();
		teacher.setName(result.get());
		try {
			teacherDAO.save(teacher);
			pushToTextArea("添加老师：" + result.get() + "成功");
		} catch (RuntimeException e) {
			pushToTextArea("添加老师失败");
		}
	}

	/**
	 * 更新老师信息
	 * 
	 * @param actionEvent
	 * @throws Exception
	 */
	public void onUpdateTeacher(ActionEvent actionEvent) throws Exception {
		Stage stage = new Stage();
		stage.initStyle(StageStyle.TRANSPARENT);
		new Application() {
			@Override
			public void start(Stage primaryStage) throws Exception {
				DoubleInputDialog doubleInputDialog = new DoubleInputDialog("老师编号", "新名字", "修改老师信息", primaryStage);
				doubleInputDialog.setConfirmButtonAction(onUpdateTeacherComfirm(doubleInputDialog, primaryStage));
				Scene scene = new Scene(doubleInputDialog);
				primaryStage.setScene(scene);
				primaryStage.show();
			}
		}.start(stage);
	}

	/**
	 * 老师点击确认按钮时触发的事件
	 * 
	 * @param doubleInputDialog
	 * @return
	 */
	public EventHandler<ActionEvent> onUpdateTeacherComfirm(DoubleInputDialog doubleInputDialog, Stage stage) {
		return action -> {
			Long id = Long.valueOf(doubleInputDialog.getTextField1().getText());
			Teacher teacher = teacherDAO.findById(id);
			teacher.setName(doubleInputDialog.getTextField2().getText());
			try {
				teacherDAO.update(teacher);
				pushToTextArea("更新老师信息成功，新老师信息是: ");
				pushToTextArea(teacher.toString());
			} catch (RuntimeException e) {
				pushToTextArea("更新失败");
			}
			stage.close();
		};
	}

	/**
	 * 删除老师
	 * 
	 * @param actionEvent
	 */
	public void onDeleteTeacher(ActionEvent actionEvent) {
		TextInputDialog dialog = new TextInputDialog();
		dialog.setTitle("删除老师");
		dialog.setHeaderText(null);
		dialog.setContentText("老师编号");
		Optional<String> result = dialog.showAndWait();
		// 用户点击取消
		if (!result.isPresent()) {
			return;
		}
		Teacher teacher = new Teacher();
		teacher.setId(Long.valueOf(result.get()));
		try {
			teacherDAO.delete(teacher);
			pushToTextArea("删除老师编号：" + result.get() + "成功");
		} catch (RuntimeException e) {
			pushToTextArea("删除老师失败");
		}
	}

	/**
	 * 搜索老师的学生
	 * 
	 * @param actionEvent
	 */
	public void onChooseStudent(ActionEvent actionEvent) {
		TextInputDialog dialog = new TextInputDialog();
		dialog.setTitle("搜索老师的学生");
		dialog.setHeaderText(null);
		dialog.setContentText("老师编号");
		Optional<String> result = dialog.showAndWait();
		// 用户点击取消
		if (!result.isPresent()) {
			return;
		}
		Long id = Long.valueOf(result.get());
		try {
			Teacher teacher = teacherDAO.findById(id);
			pushToTextArea(teacher.toString());
			pushToTextArea("他的学生如下");
			for (Object o : studentDAO.findByProperty("tutor", id)) {
				pushToTextArea(o.toString());
			}
			pushToTextArea("他的学生如上");
		} catch (RuntimeException e) {
			pushToTextArea("搜索老师的学生");
		}
	}

	/**
	 * 教师修改学生的指导老师
	 * 
	 * @param actionEvent
	 * @throws Exception
	 */
	public void onUpdateInstructedStudent(ActionEvent actionEvent) throws Exception {
		Stage stage = new Stage();
		stage.initStyle(StageStyle.TRANSPARENT);
		new Application() {
			@Override
			public void start(Stage primaryStage) throws Exception {
				DoubleInputDialog doubleInputDialog = new DoubleInputDialog("学生编号", "新老师编号", "教师修改学生的指导老师",
						primaryStage);
				doubleInputDialog
						.setConfirmButtonAction(onUpdateInstructedStudentComfirm(doubleInputDialog, primaryStage));
				Scene scene = new Scene(doubleInputDialog);
				primaryStage.setScene(scene);
				primaryStage.show();
			}
		}.start(stage);
	}

	/**
	 * 添加学生点击确认按钮时触发的事件
	 * 
	 * @param doubleInputDialog
	 * @return
	 */
	public EventHandler<ActionEvent> onUpdateInstructedStudentComfirm(DoubleInputDialog doubleInputDialog,
			Stage stage) {
		return action -> {
			Long id = Long.valueOf(doubleInputDialog.getTextField1().getText());
			Student student = studentDAO.findById(id);
			Long tutor = Long.valueOf(doubleInputDialog.getTextField2().getText());
			student.setTutor(tutor);
			try {
				studentDAO.update(student);
				pushToTextArea("更新学生的指导老师成功");
				pushToTextArea("新学生信息是" + student);
				if (student.getTutor() != null) {
					pushToTextArea("新指导老师是：");
					pushToTextArea(teacherDAO.findById(student.getTutor()).toString());
				}
			} catch (RuntimeException e) {
				pushToTextArea("更新失败");
			}
			stage.close();
		};
	}

	/**
	 * 把提示信息推进界面
	 * 
	 * @param contents
	 */
	private void pushToTextArea(String... contents) {
		StringBuilder stringBuilder = new StringBuilder();
		for (String content : contents) {
			stringBuilder.append(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss")))
					.append("#").append(content).append("\n");
		}
		last = last + stringBuilder.toString();
		textArea.setText(last);
	}

}
